package cn.readjava.realm;

import cn.readjava.bean.User;
import cn.readjava.constant.ShiroConstant;
import cn.readjava.service.PermissionService;
import cn.readjava.service.RoleService;
import cn.readjava.service.UserService;
import cn.readjava.shiro.UserToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
public class AdminShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        log.info("【管理员授权】doGetAuthorizationInfo...");
        User user = (User) principalCollection.getPrimaryPrincipal();
        // 查找角色和权限
        Set<String> roles = roleService.findAllRole(user.getUserId());
        Set<String> permissions = permissionService.findAllPermission(user.getUserId());
        // 授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        log.info("【管理员认证】doGetAuthenticationInfo...");
        UserToken userToken = (UserToken) token;
        User user = userService.findByUserName(userToken.getUsername());
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        String salt = user.getUserId() + ShiroConstant.SALT;
        return new SimpleAuthenticationInfo(user, user.getUserPassword(), ByteSource.Util.bytes(salt), getName());
    }
}
